<?php

require_once("lib/exception/duplicate_instance_exception.php");
require_once("lib/exception/internal_error_exception.php");
require_once("lib/exception/instance_not_found_exception.php");

require_once("lib/model/action.php");
require_once("model/article_category/to/article_category_to.php");
require_once("model/article/to/article_to.php");
require_once("model/article_article_category/to/article_article_category_to.php");
require_once("model/article_article_category/dao/article_article_category_dao_factory.php");

class Create_article_category_action implements Action {

	private $article_to;
	private $category_list;
	
	public function __construct($article_to, $category_list) {
		
		$this->article_to = $article_to;
		$this->category_list = $category_list;
	}
	
	public function do_execute() {
		try {

			$dao = Article_article_category_dao_factory::singleton()->get_dao();
			
			foreach($this->category_list as $category_to)
				if (!$dao->exist($this->article_to->get_number(),$category_to->get_number()))
					$dao->create($this->article_to->get_number(),$category_to->get_number());	
			
			$dao = Article_dao_factory::singleton()->get_dao();
			$article_to = $dao->find_by_number_article($this->article_to->get_number());
			if ($article_to->get_state() == 'wait') {
				$article_to->set_state('open');
				$dao->update($article_to);
			}
			
		}
		catch (Instance_not_found_exception $e) {
			throw new Model_exception($e);
		}
		catch (Duplicate_instance_exception $e) {
			throw new Model_exception($e);
		}
		catch (Internal_error_exception $e) {
			throw $e;
		}
		catch (Exception $e) {
			throw new Exception("Internal error exception --> " . $e);
		}
	}
	
}

?>